<?php
namespace app\wxapp\controller;
use think\Controller;
use think\Db;
class Login extends Controller {

    public $appid = 'wxb472da012e9658b4',
           $secret = '793ed381bce4c77dec4017a27781615d';

    public function index()
    {
        $redirect_url = urlencode('http://'.$_SERVER['HTTP_HOST'].url('login/check'));  //需添加授信域名
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$redirect_url.'&response_type=code&scope=snsapi_userinfo#wechat_redirect';
        echo '<script>location="'.$url.'";</script>';
    }

    public function base64_set($base)
    {
        $result = '';
        for($i=strlen($base)-1;$i>=0;$i--){
            $result .= $base[$i];
        }
        return $result;
    }

    //请求安全稍稍加密,逆天少侠独创
    public function token_encode($id)
    {
        $time = time();
        return $this->base64_set(base64_encode(($time^$id)."_".$time));
    }

    public function check()
    {
        $code = $_GET['code'];
        if($code){
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->secret.'&code='.$code.'&grant_type=authorization_code';
            $content = file_get_contents($url);
            $json = json_decode($content);
            $access_token = $json->access_token;
            $openid = $json->openid;
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
            $user_info = file_get_contents($url);
            $json = json_decode($user_info);
            $name = $json->nickname;
            $headimg = $json->headimgurl;
            $other_id = $json->unionid;
            $check = Db::table('user')->where('other_id',$other_id)->find();
            if(count($check) == 0){
                $id = Db::table('user')->insertGetId(['other_id'=>$other_id,'name'=>'用户'.time(),'headimg'=>$headimg,'name'=>$name]);
            }else{
                $id = $check['id'];
            }
            $token = $this->token_encode($id);
            $this->redirect(url('home/index').'?token='.$token.'&openid='.$openid);
        }
    }
}